package com.happy.cat.project.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.happy.cat.common.utils.StringUtils;
import com.happy.cat.common.utils.poi.ExcelUtil;
import com.happy.cat.framework.web.controller.BaseController;
import com.happy.cat.framework.web.domain.AjaxResult;
import com.happy.cat.framework.web.page.TableDataInfo;
import com.happy.cat.project.system.domain.UserAccount;
import com.happy.cat.project.system.domain.UserCardVoucher;
import com.happy.cat.project.system.domain.UserOrder;
import com.happy.cat.project.system.domain.vo.UserOrderVo;
import com.happy.cat.project.system.service.IUserAccountService;
import com.happy.cat.project.system.service.IUserCardVoucherService;
import com.happy.cat.project.system.service.IUserOrderService;
import com.happy.cat.framework.aspectj.lang.annotation.Log;
import com.happy.cat.framework.aspectj.lang.enums.BusinessType;
import com.happy.cat.project.system.domain.CatTeamCategoryItem;
import com.happy.cat.project.system.domain.CatTeamCategoryTag;
import com.happy.cat.project.system.service.ICatTeamCategoryItemService;
import com.happy.cat.project.system.service.ICatTeamCategoryTagService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 用户订单Controller
 *
 * @author verne
 * @date 2020-08-12
 */
@AllArgsConstructor
@RestController
@RequestMapping("/system/userOrder" )
@Api("用户订单 API")
public class UserOrderController extends BaseController {

    private final IUserOrderService iUserOrderService;

    @Autowired
    private IUserAccountService userAccountService;

    @Autowired
    private ICatTeamCategoryItemService teamCategoryItemService;

    @Autowired
    private ICatTeamCategoryTagService teamCategoryTagService;

    @Autowired
    private IUserCardVoucherService cardVoucherService;


    /**
     * 查询用户订单列表
     */
    @ApiOperation(value = "查询用户订单列表",notes = "查询用户订单列表",response = TableDataInfo.class)
    @PreAuthorize("@ss.hasPermi('system:userOrder:list')")
    @GetMapping("/list")
    public TableDataInfo list(UserOrder userOrder)
    {
        startPage();
        LambdaQueryWrapper<UserOrder> lqw = new LambdaQueryWrapper<UserOrder>();
        if (userOrder.getBookingId() != null){
            lqw.eq(UserOrder::getBookingId ,userOrder.getBookingId());
        }
        if (userOrder.getAccompanyId() != null){
            lqw.eq(UserOrder::getAccompanyId ,userOrder.getAccompanyId());
        }
        if (userOrder.getNumber() != null){
            lqw.eq(UserOrder::getNumber ,userOrder.getNumber());
        }
        if (userOrder.getScore() != null){
            lqw.eq(UserOrder::getScore ,userOrder.getScore());
        }
        if (userOrder.getVoucherCardId() != null){
            lqw.eq(UserOrder::getVoucherCardId ,userOrder.getVoucherCardId());
        }
        if (userOrder.getRegionId() != null){
            lqw.eq(UserOrder::getRegionId ,userOrder.getRegionId());
        }
        if (userOrder.getTotalPrice() != null){
            lqw.eq(UserOrder::getTotalPrice ,userOrder.getTotalPrice());
        }
        if (userOrder.getDifferencePrice() != null){
            lqw.eq(UserOrder::getDifferencePrice ,userOrder.getDifferencePrice());
        }
        if (userOrder.getPaidPrice() != null){
            lqw.eq(UserOrder::getPaidPrice ,userOrder.getPaidPrice());
        }
        if (userOrder.getStatus() != null){
            lqw.eq(UserOrder::getStatus ,userOrder.getStatus());
        }
        if (StringUtils.isNotBlank(userOrder.getPaymentMethod())){
            lqw.eq(UserOrder::getPaymentMethod ,userOrder.getPaymentMethod());
        }
        if (StringUtils.isNotBlank(userOrder.getOrderChannel())){
            lqw.eq(UserOrder::getOrderChannel ,userOrder.getOrderChannel());
        }
        if (userOrder.getPayTime() != null){
            lqw.eq(UserOrder::getPayTime ,userOrder.getPayTime());
        }
        if (userOrder.getOrderTime() != null){
            lqw.eq(UserOrder::getOrderTime ,userOrder.getOrderTime());
        }
        if (userOrder.getOrderIncome() != null){
            lqw.eq(UserOrder::getOrderIncome ,userOrder.getOrderIncome());
        }
        List<UserOrder> list = iUserOrderService.list(lqw);
        if(list.size()<=0){
            return getDataTable(list);
        }


        Set<Long> userIds = new HashSet<>();
        Set<Long> gameIds = new HashSet<>();
        Set<Long> regionIds = new HashSet<>();

        Set<Long> voucherCardIds = new HashSet<>();

        List<UserOrderVo> vos = new ArrayList<>();
        list.forEach(e->{
            userIds.add(e.getBookingId());
            userIds.add(e.getAccompanyId());

            gameIds.add(e.getGameId());

            regionIds.add(e.getRegionId());

            voucherCardIds.add(e.getVoucherCardId());
            vos.add(e.convertToVo());
        });

        Map<Long, UserAccount> userMap = userAccountService.listByIds(userIds).stream().collect(Collectors.toMap(UserAccount::getId, e -> e));
        Map<Long, CatTeamCategoryItem> gameMap = teamCategoryItemService.listByIds(gameIds).stream().collect(Collectors.toMap(CatTeamCategoryItem::getId, e -> e));
        Map<Long, CatTeamCategoryTag> regionMap = teamCategoryTagService.listByIds(regionIds).stream().collect(Collectors.toMap(CatTeamCategoryTag::getId, e -> e));
        Map<Long, UserCardVoucher> cardMap = cardVoucherService.listByIds(voucherCardIds).stream().collect(Collectors.toMap(UserCardVoucher::getId, e -> e));

        vos.forEach(e -> {
            UserAccount user = userMap.get(e.getBookingId());
            if(user!=null){
                e.setBookingName(user.getNick());
                e.setBookingCode(user.getCatCode().toString());
            }
            user = userMap.get(e.getAccompanyId());
            if(user!=null){
                e.setAccompanyName(user.getNick());
                e.setAccompanyCode(user.getCatCode().toString());
            }
            CatTeamCategoryItem game = gameMap.get(e.getGameId());
            if(game!=null){
                e.setGameName(game.getName());
                e.setUnit(game.getTollType());
            }
            if(regionMap.get(e.getRegionId())!=null){
                e.setRegionName(regionMap.get(e.getRegionId()).getName());
            }
            if(cardMap.get(e.getVoucherCardId())!=null){
                e.setVoucherCardAmount(cardMap.get(e.getVoucherCardId()).getCardAmount());
            }
        });
        return getDataTable(vos);
    }

    /**
     * 导出用户订单列表
     */
    @ApiOperation(value = "导出用户订单列表",notes = "导出用户订单列表",response = AjaxResult.class)
    @PreAuthorize("@ss.hasPermi('system:userOrder:export')" )
    @Log(title = "用户订单" , businessType = BusinessType.EXPORT)
    @GetMapping("/export" )
    public AjaxResult export(UserOrder userOrder) {
        LambdaQueryWrapper<UserOrder> lqw = new LambdaQueryWrapper<UserOrder>(userOrder);
        List<UserOrder> list = iUserOrderService.list(lqw);
        ExcelUtil<UserOrder> util = new ExcelUtil<UserOrder>(UserOrder. class);
        return util.exportExcel(list, "userOrder" );
    }

    /**
     * 获取用户订单详细信息
     */
    @ApiOperation(value = "获取用户订单详细信息",notes = "获取用户订单详细信息",response = AjaxResult.class)
    @PreAuthorize("@ss.hasPermi('system:userOrder:query')" )
    @GetMapping(value = "/{id}" )
    public AjaxResult getInfo(@PathVariable("id" ) Long id) {
        return AjaxResult.success(iUserOrderService.getById(id));
    }

    /**
     * 新增用户订单
     */
    @ApiOperation(value = "新增用户订单",notes = "新增用户订单",response = AjaxResult.class)
    @PreAuthorize("@ss.hasPermi('system:userOrder:add')" )
    @Log(title = "用户订单" , businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody UserOrder userOrder) {
        return toAjax(iUserOrderService.save(userOrder) ? 1 : 0);
    }

    /**
     * 修改用户订单
     */
    @ApiOperation(value = "修改用户订单",notes = "修改用户订单",response = AjaxResult.class)
    @PreAuthorize("@ss.hasPermi('system:userOrder:edit')" )
    @Log(title = "用户订单" , businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody UserOrder userOrder) {
        return toAjax(iUserOrderService.updateById(userOrder) ? 1 : 0);
    }

    /**
     * 删除用户订单
     */
    @ApiOperation(value = "删除用户订单",notes = "删除用户订单",response = AjaxResult.class)
    @PreAuthorize("@ss.hasPermi('system:userOrder:remove')" )
    @Log(title = "用户订单" , businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}" )
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(iUserOrderService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }
}
